﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Kratos.Framework.ContentManagement.Models;

namespace Kratos.Framework.Infrastructures
{
    public static class SecurityHelper
    {
        /// <summary>
        /// 全局的
        /// </summary>
        public static readonly IList<ActionPermission> Actions;

        static SecurityHelper()
        {
            Actions = new List<ActionPermission>();
        }

        /// <summary>
        /// 反射获取当前系统所有的Action
        /// </summary>
        /// <returns></returns>
        public static void SetActionByAssembly(Assembly assembly)
        {
            if (assembly == null) throw new ArgumentNullException("assembly");

            var types = assembly.GetTypes();
            foreach (var type in types.Where(t => t.BaseType != null && t.BaseType.Name == "KratosController"))
            {
                var members = type.GetMethods();

                var attrsOfController = type.GetCustomAttributes(typeof(DescriptionAttribute), true);
                DescriptionAttribute controllerAttr = null;
                if (attrsOfController.Length > 0)
                    controllerAttr = attrsOfController[0] as DescriptionAttribute;

                foreach (var member in members.Where(m => m.ReturnType.Name == "ActionResult"))
                {
                    var ap = new ActionPermission
                                 {
                                     ActionName = member.Name,
                                     ControllerName =
                                         // 去掉“Controller”后缀
                                         member.DeclaringType.Name.Substring(0,
                                                                             member.DeclaringType.Name.Length -
                                                                             10)
                                 };

                    var attrsOfAction = member.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (attrsOfAction.Length > 0)
                    {
                        var descriptionAttribute = attrsOfAction[0] as DescriptionAttribute;
                        if (descriptionAttribute != null)
                            ap.ActionDescription = descriptionAttribute.Description;
                    }

                    if (controllerAttr != null)
                        ap.ControllerDescription = controllerAttr.Description;

                    Actions.Add(ap);
                }
            }
        }
    }
}
